<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="110px"
            v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" clearable class="!w-240px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>

<!--suppress HtmlUnknownAttribute -->
<script setup lang="ts" name="${entity}Form">
  import * as ${entity}Api from '@/api/${apiPath}'

  const { t } = useI18n()
  const message = useMessage()

  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const formLoading = ref(false)
  const formType = ref('')
  const formData = ref<any>({
    id: undefined,
    name: undefined
  })
  const formRules = reactive({
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
  })
  const formRef = ref()

  const open = async (type: string, id?: number | string) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    if (id) {
      formLoading.value = true
      try {
        formData.value = await ${entity}Api.getDetailById(id)
      } finally {
        formLoading.value = false
      }
    }
  }
  defineExpose({ open })

  const emit = defineEmits(['success'])
  const submitForm = async () => {
    if (!formRef) {
      return
    }
    try {
      const valid = await formRef.value.validate()
      if (!valid) {
        return
      }
      formLoading.value = true
      if (formType.value === 'create') {
        await ${entity}Api.create(formData.value)
        message.success(t('common.createSuccess'))
      } else {
        await ${entity}Api.updateById(formData.value)
        message.success(t('common.updateSuccess'))
      }
      dialogVisible.value = false
      emit('success')
    } catch (e) {
      console.error('submit error', e)
    } finally {
      formLoading.value = false
    }
  }

  const resetForm = () => {
    formData.value = {
      id: undefined,
      name: undefined
    }
    formRef.value?.resetFields()
  }
</script>
